package com.mti.monitor.scheduled;

import com.mti.monitor.bean.model.SysMonitorConfig;
import com.mti.monitor.config.DataSourceContextHolder;
import com.mti.monitor.config.properties.Constants;
import com.mti.monitor.enums.TaskTypeEnum;
import com.mti.monitor.mapper.SysMonitorConfigMapper;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class InitScheduled implements CommandLineRunner {

    @Autowired
    private ScheduledConfig scheduledConfig;

    @Autowired
    private SysMonitorConfigMapper sysMonitorConfigMapper;


    @Override
    @SneakyThrows
    public void run(String... args) {
        DataSourceContextHolder.clearDataSourceType();
        List<SysMonitorConfig> monitorList = sysMonitorConfigMapper.selectActiveList();
        List<SysMonitorConfig> extMonitorList = new ArrayList<>();
        //如果是服务类监控，主动增加每6小时监控该服务是否正常
        for(SysMonitorConfig e : monitorList){
            if(e.getTaskType().equals(TaskTypeEnum.SERVER.getType())){
                SysMonitorConfig config = new SysMonitorConfig();
                BeanUtils.copyProperties(e,config);
                config.setId(config.getId() + Constants.TASK_NAME_EXT);
                config.setScheduledCron(Constants.TASK_EXT_CRON);
                extMonitorList.add(config);
            }
        }
        monitorList.addAll(extMonitorList);
        scheduledConfig.refresh(monitorList);
    }
}
